<?php
/**
 * Date: 2018/2/5
 * Time: 11:31
 * Author: zeronlee
 */

namespace App\Models\Orders;

use Arcanedev\Support\Bases\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Orders\Traits\Relationship\OrderRelationship;

class Order extends Model
{

    use softDeletes,OrderRelationship;

    protected $table = 'orders';

    protected $primaryKey = 'id';

    public $timestamps = true;

    protected $guarded = ['column'];

    protected $fillable = [];

    protected $dates = ['delete_at'];

    public $status = [0=>'待支付',1=>'待发货',2=>'待收货',3=>'待评价',4=>'已关闭'];

    /**
     * 查询列表的另一种方法
     * 用作性能调试 打出和lists的sql分别对比
     * @param $request
     * @return mixed
     */
    public function list1($request){
        $res = collect();
        //fields
        $select = ['orders.*','orders.num as goods_num'];
        //order
        $orderBy = ['column'=>'orders.'.$request->orderColumn,'direction'=>$request->orderDir];
        //page
        $page = ['offset'=>$request->start,'limit'=>$request->length];
        $orders = $this->select($select);
        if (isset($request->status) && $request->status >= 0){

            $orders = $orders->where('status',$request->status);
        }
        if (isset($request->keyworld) && $request->keyworld){
            $orders = $orders->where(function ($query) use ($request){
                $query->where('sn','like',$request->keyworld . '%')
                    ->orWhere('consignee','like',$request->keyworld . '%')
                    ->OrWhereHas('user',function ($query) use ($request){
                        $query->where('name','like',$request->keyworld . '%');
                    })
                    ->orWhereHas('goods',function ($query) use ($request){
                        $query->where('name','like',$request->keyworld . '%');
                    });
            });
        }
        $res->count = $orders->count();
        $orders = $orders->orderBy($orderBy['column'],$orderBy['direction'])
            ->offset($page['offset'])
            ->limit($page['limit'])
            ->get();
        foreach ($orders as $order){
            //无法查询关联表字段 这里多次查询耗时耗力
            $order['user_name'] = $order->user->name;
            $order['goods_name'] = $order->goods->name;
        }
        $res->list = $orders;
        //适合查询主表单表数据
        return $res;
    }
    /**
     * @param $request
     * @return mixed
     */
    public function lists($request){
        $res = collect();
        //fields
        $select = ['orders.*','orders.num as goods_num','goods.name as goods_name','users.name as user_name','users.real_name'];
        $builder = $this->select($select);
        if (isset($request->deleted_at) && $request->deleted_at){
            //只取删除的
            $builder = $builder->onlyTrashed();
        }
        //where
        if (isset($request->status) && $request->status >= 0){

            $builder = $builder->where('orders.status',$request->status);
        }
        if (isset($request->keyworld) && $request->keyworld){
            //group
            $builder = $builder->where(function ($query) use ($request){
                $query->where('orders.sn','like',$request->keyworld.'%')
                    ->orWhere('orders.consignee','like',$request->keyworld.'%')
                    ->orWhere('users.name','like',$request->keyworld.'%')
                    ->orWhere('goods.name','like',$request->keyworld.'%');
            });
        }
        //order
        $orderBy = ['column'=>'orders.'.$request->orderColumn,'direction'=>$request->orderDir];
        //page
        $page = ['offset'=>$request->start,'limit'=>$request->length];
        $builder = $builder->leftJoin('users',function ($join){
            $join->on("orders.user_id","=","users.id");
        });
        $builder = $builder->leftJoin('goods',function ($join){
            $join->on("orders.goods_id","=","goods.id");
        });
        $res->count = $builder->count();
        $res->list = $builder->orderBy($orderBy['column'],$orderBy['direction'])
            ->offset($page['offset'])
            ->limit($page['limit'])
            ->get();
        return $res;
    }
    /**
     * 插入记录
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function insertRow($request){

        if ($this->save($request->input())) {


            return true;
        }

        throw new \Exception('添加失败');

    }
    /**
     * 修改记录
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function updateRow($request){

        $update = $this->find($request->id);

        if($update->update($request->input())){

            return true;
        }
        throw new \Exception('更新失败');
    }
    /**
     * 删除记录
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function deleteRow($request){
        if (empty($request->id)){
            throw new \Exception('非法操作');
        }
        $del = $this->find($request->id);
        $del->delete();
        if ($del->trashed()) {
            return true;
        }else{

            throw new \Exception('禁用失败');
        }

    }
    /**
     * 激活
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function activeRow($request){

        $active = $this->withTrashed()->find($request->id);
        //避免禁用用户二次进入
        if ($active){
            $active->deleted_at = NULL;
            if ($active->save()){
                return true;
            }
        }
        return false;

    }
    /**
     * 物理删除
     * @param mixed $request
     * @return bool
     * @throws \Exception
     */
    public function forceDelOrder($request){

        $forceDel = $this->withTrashed()->find($request->id);

        if ($forceDel){

            if ($forceDel->forceDelete()){
                return true;
            }
        }
        return false;

    }
}